package com.qiyun.dinghuohui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qiyun.dinghuohui.R;
import com.qiyun.dinghuohui.base.BaseActivity;
import com.qiyun.dinghuohui.common.ClientCookie;
import com.qiyun.dinghuohui.common.CommonDataSets;
import com.qiyun.dinghuohui.common.GlideImageLoader;
import com.qiyun.dinghuohui.utils.CommonUtil;
import com.qiyun.dinghuohui.utils.Inject;
import com.qiyun.dinghuohui.utils.LogDebug;
import com.qiyun.dinghuohui.utils.ServerResponse;
import com.qiyun.dinghuohui.vo.PublicSelectParamBean;
import com.qiyun.dinghuohui.widget.MyKeyboard;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by xlm on 2018/6/7
 */

public class PairDetailActivity extends BaseActivity {
    @Inject(R.id.back)
    private RelativeLayout mRelaBack;//返回
    @Inject(R.id.title)
    private TextView mTxtTitle;//标题栏(编号，货号)
    @Inject(R.id.submit_btn)
    private TextView mTxtSubmitBtn;//提交按钮
    @Inject(R.id.banner)
    private Banner banner;

    @Inject(R.id.color_part)
    private TagFlowLayout colorsTable; //颜色标签
    @Inject(R.id.size_data)
    private TagFlowLayout sizeTable; //尺码标签
    @Inject(R.id.amount_count)
    private TagFlowLayout countTable; //合计
    @Inject(R.id.count_edit)
    private LinearLayout editTable; //编辑标签
    @Inject(R.id.order_count)
    private TextView mTxtCount;

    @Inject(R.id.pair1_info)
    private TextView mTxtPair1Info;
    @Inject(R.id.pair1_price)
    private TextView mPrice1;

    @Inject(R.id.color_part_2)
    private TagFlowLayout colorsTable2; //颜色标签
    @Inject(R.id.size_data_2)
    private TagFlowLayout sizeTable2; //尺码标签
    @Inject(R.id.amount_count_2)
    private TagFlowLayout countTable2; //合计
    @Inject(R.id.count_edit_2)
    private LinearLayout editTable2; //编辑标签
    @Inject(R.id.order_count_2)
    private TextView mTxtCount2;


    @Inject(R.id.pair2_info)
    private TextView mTxtPair2Info;
    @Inject(R.id.pair2_price)
    private TextView mPrice2;

    @Inject(R.id.focus)
    private EditText focus;

    private JSONObject object = null;
    private String pairId;

    private boolean isShowhand = false;

    private String[] colors;//颜色
    private String[] s_new;//尺码

    private String[] colors2;//颜色
    private String[] s_new2;//尺码

    private JSONObject pair_1;//搭配第一件
    private JSONObject pair_2;//搭配第二件

    private List<Integer> amount = new ArrayList<>();
    private List<Integer> amount2 = new ArrayList<>();


    public static void startActivity(Activity context, JSONObject object) {
        Intent intent = new Intent(context, PairDetailActivity.class);
        intent.putExtra("data", object.toString());
        context.startActivity(intent);
    }

    @Override
    protected void onGetIntent(Intent intent) {
        super.onGetIntent(intent);
        if (intent != null) {
            try {
                object = new JSONObject(intent.getStringExtra("data"));
                pairId = object.optString("pair_id");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_pair_detail);
    }

    @Override
    protected void initViews() {
        if (!CommonUtil.isEmpty(pairId)) {
            mTxtTitle.setText(String.valueOf(pairId + "搭配"));
        }
        banner.setImages(getImagesPath()).isAutoPlay(false)
                .setImageLoader(new GlideImageLoader()).start();
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (position == 0) {
                    BigPictureActivity.startActivity(getThis(), getImagesPath().get(position));
                }
            }
        });
    }

    @Override
    protected void onSetListener() {
        mRelaBack.setOnClickListener(getThis());
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
        }
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        pair_1 = CommonDataSets.getGoodsByCode(object.optString("code1"));
        pair_2 = CommonDataSets.getGoodsByCode(object.optString("code2"));

        setColors();
        for (String color : colors) {
            amount.add(0);
        }
        setSizes();
        setCountEdit();
        setCount();

        setColors2();
        for (String color : colors2) {
            amount2.add(0);
        }
        setSizes2();
        setCountEdit2();
        setCount2();

        setGoodInfo(mTxtPair1Info, mPrice1, pair_1);
        setGoodInfo(mTxtPair2Info, mPrice2, pair_2);
    }

    private List<JSONObject> getGoodByPair(JSONObject object) {
        List<JSONObject> list = new ArrayList<>();
        String code1 = object.optString("code1");
        String code2 = object.optString("code2");
        String code3 = object.optString("code3");
        String code4 = object.optString("code4");
        String code5 = object.optString("code5");
        String code6 = object.optString("code6");
        String code7 = object.optString("code7");
        String code8 = object.optString("code8");
        JSONObject o;
        if (!CommonUtil.isEmpty(code1)) {
            o = CommonDataSets.getGoodsByCode(code1);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code2)) {
            o = CommonDataSets.getGoodsByCode(code2);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code3)) {
            o = CommonDataSets.getGoodsByCode(code3);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code4)) {
            o = CommonDataSets.getGoodsByCode(code4);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code5)) {
            o = CommonDataSets.getGoodsByCode(code5);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code6)) {
            o = CommonDataSets.getGoodsByCode(code6);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code7)) {
            o = CommonDataSets.getGoodsByCode(code7);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code8)) {
            o = CommonDataSets.getGoodsByCode(code8);
            list.add(o);
        }
        return list;
    }

    @SuppressLint("SetTextI18n")
    private void setGoodInfo(TextView mTxtCount, TextView mTxPrice, JSONObject object) {
        String name = object.optString("name");
        String code = object.optString("code");
        String goods_code = object.optString("goods_code");
        String price = object.optString("price");
        mTxtCount.setText(name + "/" + code + "/" + goods_code);
        mTxPrice.setText("￥" + price);


    }

    //显示合计
    private void setCount() {

        countTable.setAdapter(new TagAdapter<Integer>(amount) {
            @Override
            public View getView(FlowLayout flowLayout, int i, Integer s) {
                TextView tv = (TextView) getLayoutInflater().inflate(R.layout.item_tag_common, countTable, false);
                tv.setText(String.valueOf(amount.get(i)));
                return tv;
            }
        });
    }

    //显示合计
    private void setCount2() {

        countTable2.setAdapter(new TagAdapter<Integer>(amount2) {
            @Override
            public View getView(FlowLayout flowLayout, int i, Integer s) {
                TextView tv = (TextView) getLayoutInflater().inflate(R.layout.item_tag_common, countTable2, false);
                tv.setText(String.valueOf(amount2.get(i)));
                return tv;
            }
        });
    }

    //创建输入框
    private void setCountEdit() {
        final int line = colors.length;
        final int row = s_new.length;
        final List<MyKeyboard> keyList = new ArrayList<>();
        for (int i = 0; i < line; i++) {
            LinearLayout linearLayout = new LinearLayout(this);
            linearLayout.setHorizontalGravity(LinearLayout.HORIZONTAL);
            for (int j = 0; j < row; j++) {
                //禁止系统输入法
                final MyKeyboard et = (MyKeyboard) getLayoutInflater().inflate(R.layout.item_goods_edit, linearLayout, false);
                et.setTag(i + "_" + j);
                keyList.add(et);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    et.setShowSoftInputOnFocus(false);
                }

                et.setOnKeyDown(new MyKeyboard.OnKeyDown() {

                    @Override
                    public void OnTouchDown() {
                    }

                    @Override
                    public void OnKeyDownNumber() {
                    }

                    @Override
                    public void OnKeyDownNext() {
                    }

                    @Override
                    public void OnKeyDownEnter() {
                        amount.clear();
                        int index = 1;
                        int allcount = 0;

                        int times = keyList.size() / row;
                        do {
                            List<MyKeyboard> listTemp = null;
                            listTemp = keyList.subList(row * (index - 1), row * index);// listTemp是分段处理逻辑的参数
                            //遍历当前的值是否正确
                            StringBuilder result = new StringBuilder();
                            int num = 0;
                            for (int i = 0; i < listTemp.size(); i++) {
                                String text = listTemp.get(i).getText().toString();
                                if (text.length() == 0) {
                                    text = "0";
                                }
                                num += Integer.parseInt(text);
                                result.append(listTemp.get(i).getText().toString()).append(",");
                            }

                            amount.add(num);
                            allcount += num;
                            LogDebug.d("第" + index + "轮:>>" + result + "------和------" + num);
                            index++;
                        }
                        while (index <= times);
                        setCount();
                        setCount2();
                        mTxtCount.setText(String.valueOf("合计：" + allcount + "件"));
                        for (MyKeyboard myKeyboard : keyList) {
                            myKeyboard.clearFocus();
                        }
                        focus.requestFocus();
                    }
                });
                linearLayout.addView(et);
            }

            editTable.addView(linearLayout);
        }
    }

    //创建输入框
    private void setCountEdit2() {
        final int line = colors2.length;
        final int row = s_new2.length;
        final List<MyKeyboard> keyList = new ArrayList<>();
        for (int i = 0; i < line; i++) {
            LinearLayout linearLayout = new LinearLayout(this);
            linearLayout.setHorizontalGravity(LinearLayout.HORIZONTAL);
            for (int j = 0; j < row; j++) {
                //禁止系统输入法
                final MyKeyboard et = (MyKeyboard) getLayoutInflater().inflate(R.layout.item_goods_edit, linearLayout, false);
                et.setTag(i + "_" + j);
                keyList.add(et);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    et.setShowSoftInputOnFocus(false);
                }

                et.setOnKeyDown(new MyKeyboard.OnKeyDown() {

                    @Override
                    public void OnTouchDown() {
                    }

                    @Override
                    public void OnKeyDownNumber() {
                    }

                    @Override
                    public void OnKeyDownNext() {
                    }

                    @Override
                    public void OnKeyDownEnter() {
                        amount2.clear();
                        int index = 1;
                        int allcount = 0;

                        int times = keyList.size() / row;
                        do {
                            List<MyKeyboard> listTemp = null;
                            listTemp = keyList.subList(row * (index - 1), row * index);// listTemp是分段处理逻辑的参数
                            //遍历当前的值是否正确
                            StringBuilder result = new StringBuilder();
                            int num = 0;
                            for (int i = 0; i < listTemp.size(); i++) {
                                String text = listTemp.get(i).getText().toString();
                                if (text.length() == 0) {
                                    text = "0";
                                }
                                num += Integer.parseInt(text);
                                result.append(listTemp.get(i).getText().toString()).append(",");
                            }

                            amount2.add(num);
                            allcount += num;
                            LogDebug.d("第" + index + "轮:>>" + result + "------和------" + num);
                            index++;
                        }
                        while (index <= times);
                        setCount();
                        setCount2();
                        mTxtCount2.setText(String.valueOf("合计：" + allcount + "件"));
                        for (MyKeyboard myKeyboard : keyList) {
                            myKeyboard.clearFocus();
                        }
                        focus.requestFocus();
                    }
                });
                linearLayout.addView(et);
            }

            editTable2.addView(linearLayout);
        }
    }

    //设置尺码
    private void setSizes() {
        if (pair_1 != null && pair_1.length() != 0) {
            String[] sizes = pair_1.optString("size_string").split(",");
            String[] size_new = null;
            if (isShowhand) {
                size_new = new String[sizes.length + 1];
                System.arraycopy(sizes, 0, size_new, 0, sizes.length);
                size_new[sizes.length] = "手数";
            }
            s_new = isShowhand ? size_new : sizes;

            sizeTable.setAdapter(new TagAdapter<String>(s_new) {
                @Override
                public View getView(FlowLayout flowLayout, int i, String s) {
                    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.item_tag_common, colorsTable, false);
                    tv.setText(s_new[i]);
                    return tv;
                }
            });
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(sizeTable.getLayoutParams());
            lp.width = CommonUtil.dip2px(s_new.length * 55, getThis());
            sizeTable.setLayoutParams(lp);
        }
    }

    //设置尺码
    private void setSizes2() {
        if (pair_2 != null && pair_2.length() != 0) {
            String[] sizes = pair_2.optString("size_string").split(",");
            String[] size_new = null;
            if (isShowhand) {
                size_new = new String[sizes.length + 1];
                System.arraycopy(sizes, 0, size_new, 0, sizes.length);
                size_new[sizes.length] = "手数";
            }
            s_new2 = isShowhand ? size_new : sizes;

            sizeTable2.setAdapter(new TagAdapter<String>(s_new2) {
                @Override
                public View getView(FlowLayout flowLayout, int i, String s) {
                    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.item_tag_common, colorsTable2, false);
                    tv.setText(s_new2[i]);
                    return tv;
                }
            });
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(sizeTable2.getLayoutParams());
            lp.width = CommonUtil.dip2px(s_new2.length * 55, getThis());
            sizeTable2.setLayoutParams(lp);
        }
    }

    //获取颜色标签
    private void setColors() {
        if (pair_1 != null && pair_1.length() != 0) {
            colors = pair_1.optString("color_string").split(",");
            final String[] color_new = new String[colors.length + 1];
            for (int i = 0; i < color_new.length; i++) {
                if (i == 0) {
                    color_new[0] = "";
                } else {
                    color_new[i] = colors[i - 1];
                }
            }
            colorsTable.setAdapter(new TagAdapter<String>(color_new) {
                @Override
                public View getView(FlowLayout flowLayout, int i, String s) {
                    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.item_tag_common, colorsTable, false);
                    tv.setText(color_new[i]);
                    return tv;
                }
            });
        }
    }

    //获取颜色标签
    private void setColors2() {
        if (pair_2 != null && pair_2.length() != 0) {
            colors2 = pair_1.optString("color_string").split(",");
            final String[] color_new = new String[colors2.length + 1];
            for (int i = 0; i < color_new.length; i++) {
                if (i == 0) {
                    color_new[0] = "";
                } else {
                    color_new[i] = colors2[i - 1];
                }
            }
            colorsTable2.setAdapter(new TagAdapter<String>(color_new) {
                @Override
                public View getView(FlowLayout flowLayout, int i, String s) {
                    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.item_tag_common, colorsTable2, false);
                    tv.setText(color_new[i]);
                    return tv;
                }
            });
        }
    }

    //通过code获取搭配数据,搜集搭配里边的code,拼接轮播图
    private List<String> getImagesPath() {
        Set<String> strings = new HashSet<>();
        strings.add(ClientCookie.getServerUrl() + "/goods/pair/" + "C001" + ".jpg");
        for (int i = 1; i < 9; i++) {
            String code1 = object.optString("code" + i);
            if (!CommonUtil.isEmpty(code1)) {
                String url = ClientCookie.getServerUrl() + "/goods/img/" + code1 + ".jpg";
//                    String url = ClientCookie.getServerUrl() + "/goods/img/" + "1504" + ".jpg";
                strings.add(url);
            }
        }
        return new ArrayList<>(strings);
    }


    @Override
    public void onPostDataStart() {

    }

    @Override
    public void onPostDataSuccess(ServerResponse response) {

    }

    @Override
    public void onPostDataError(ServerResponse response) {

    }

    @Override
    public void onPostDataComplete(ServerResponse response) {

    }

    @Override
    public void setProgressMessage(String message) {

    }

    @Override
    public void publicSelectCallBack(PublicSelectParamBean pspb) {

    }


}
